package com.warmheart.base.session;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.warmheart.base.config.RedisService;
import com.warmheart.base.config.SysConfig;
import com.warmheart.base.entity.Operator;
import com.warmheart.core.enums.PlatEnum;
import com.warmheart.core.util.UUIDGenerator;

/**
 * 
 * @ClassName: SessionManager
 * @Description: SESSION管理
 * @author ZhangJianyang
 * @date 2025-06-16 09:37:02
 *
 */
@Component
public class SessionManager {

    @Autowired(required = false)
    private RedisService redisService;

    @Autowired(required = false)
    private SysConfig sysConfig;

    // REDIS缓存前缀
    private final String PRE_FIX = PlatEnum.RedisPrefix.PREFIX_WEB.getValue() + "SESSION_";

    /**
     * @function 将当前操作用户数据存入REDIS
     * @param sessionId
     * @param operator
     * @return void
     */
    public String setOperator(Operator operator) {
        String sessionId = UUIDGenerator.getUUID();
        operator.setSessionId(sessionId);
        redisService.set(PRE_FIX + sessionId, operator, sysConfig.getSessionExpire());
        return sessionId;
    }

    /**
     *
     * @Title: get
     * @Description: 获取到REDIS信息
     * @param sessionId
     * @return
     */
    public Object get(String sessionId) {
        return redisService.get(PRE_FIX + sessionId);
    }

    /**
     * 获取用户对象
     * 
     * @param request
     * @param cookieType
     * @return
     */
    public Operator getOperator(HttpServletRequest request) {
        String sessionId = getSessionIdByToken(request);
        if (StringUtils.isBlank(sessionId)) {
            return null;
        }
        return redisService.getObject(PRE_FIX + sessionId, Operator.class);
    }

    /**
     * 前端自定义token
     * 
     * @param request
     * @return
     */
    public String getSessionIdByToken(HttpServletRequest request) {
        String sessionId = request.getHeader("X-Token");
        return sessionId;
    }

    /**
     * @function 重设用户session（刷新）session失效日期
     * @param request
     * @return
     * @return SessionUser
     */
    public Long resetOperator(HttpServletRequest request) {
        Operator operator = getOperator(request);
        if (operator != null) {
            redisService.expire(PRE_FIX + operator.getSessionId().toString(), sysConfig.getSessionExpire());
        }
        return null;
    }

    /**
     * @function 删除缓存
     * @param key
     * @return
     * @return SessionUser
     */
    public void del(String key) {
        if (!StringUtils.isBlank(key)) {
            redisService.del(PRE_FIX + key);
        }
    }
}
